package com.itcam.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @author : Cammy.Wu
 * Description : 生产者
 */

public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1.kafka连接配置信息
        Properties prop = new Properties();
        // 连接配置
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        // key和value的序列化器
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        // ack——消息确认机制
        prop.put(ProducerConfig.ACKS_CONFIG, "all");

        // 重试次数
        prop.put(ProducerConfig.RETRIES_CONFIG, 3);

        // 消息压缩
        prop.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");

        // 2.创建kafka生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(prop);

        // 3.发送消息
        /*
            ProducerRecord
                第一个参数：topic
                第二个参数：消息的key
                第三个参数：消息的value
         */
        ProducerRecord<String, String> producerRecord = new ProducerRecord<>("topic_first", "hello kafka");
        // 发送同步消息
        // RecordMetadata recordMetadata = producer.send(producerRecord).get();
        // System.out.println(recordMetadata.offset());

        // 发送异步消息
        producer.send(producerRecord, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    System.out.println("记录异常信息到日志表中");
                }
                System.out.println(recordMetadata.offset());
            }
        });

        // 4.关闭消息通道——必须要关闭，否则消息发送不成功
        producer.close();
    }
}
